package com.yatu.codegen.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.yatu.codegen.bean.TableField;
import com.yatu.codegen.util.ConvertUtil;

public class DBServiceImpl implements DBService {
	Connection conn = null;
	Statement st = null;
	ResultSet rs = null;
	PreparedStatement pst = null;
	String sqlstr = null;

	public List<TableField> getAllColums(String tableName) {
		DBConn dbConn = new DBConn();
		this.conn = dbConn.getConnection();
		List<TableField> returnList = new ArrayList<TableField>();
		try {
			Statement stmt = conn.createStatement();
			String sql = " show full columns from " + tableName;
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				TableField field = new TableField();

				field.setCollation(rs.getString("Collation"));
				field.setComment(rs.getString("Comment"));
				field.setDefaultValue(rs.getString("Default"));
				field.setField(rs.getString("Field").toUpperCase());
				field.setFieldName(ConvertUtil.convert(field.getField()));
				field.setIsAutoIncrement(rs.getString("Extra").startsWith("auto"));
				field.setIsKey(rs.getString("Key").startsWith("PRI"));
				field.setIsNull(rs.getString("Null").toUpperCase().equals("YES"));
				field.setPrivileges(rs.getString("Privileges"));
				field.setType(ConvertUtil.getTypeName(rs.getString("Type")));
				returnList.add(field);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbConn.closeALL(conn, st, rs, pst);
		}
		return returnList;
	}

	@Override
	public List<String> getTables(String database, String... excludes) {
		DBConn dbConn = new DBConn();
		List<String> databases = new ArrayList<String>();
		this.conn = dbConn.getConnection();
		Statement stmt;
		try {
			stmt = conn.createStatement();
			String sql = "show tables from " + database;
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				boolean b = false;
				for (String exclude : excludes) {
					if (exclude.equals(rs.getString(1))) {
						b = true;
					}
				}
				if (!b) {
					databases.add(rs.getString(1));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return databases;
	}
}
